#include "Channel.h"
#include "TimeStamp.h"

#include <cassert>
#include <iostream>
#include <memory>
#include <sstream>
#include <poll.h>

using std::ostringstream;

//静态变量初始化
const int Channel::kReadEvent = POLLIN | POLLPRI;
const int Channel::kWriteEvent = POLLOUT;
const int Channel::kNoneEvent = 0;

Channel::Channel(EventLoop *loop, int fd)
: _loop(loop)
, _fd(fd)
, _events(0)
, _revents(0)
, _index(-1)
, _logHup(true)
, _tied(false)
, _eventHanding(false)
, _addedToLoop(false)
{}

/* Channel::~Channel() */
/* { */
/* } */

void Channel::tie(const shared_ptr<void> &obj)
{
    _tie = obj;
    _tied = true;
}

void Channel::update()
{
    _addedToLoop = true;
    /* _loop->updateChannel(this); */
}

void Channel::remove()
{
    assert(isNoneEvent());
    _addedToLoop = false;
    /* _loop->removeChannel(this); */
}

void Channel::handleEvent(TimeStamp recvTime)
{

}

string Channel::reventsToString() const
{
  return eventsToString(_fd, _revents);
}

string Channel::eventsToString() const
{
  return eventsToString(_fd, _events);
}

string Channel::eventsToString(int fd, int ev)
{
  ostringstream oss;
  oss << fd << ": ";
  if (ev & POLLIN)
    oss << "IN ";
  if (ev & POLLPRI)
    oss << "PRI ";
  if (ev & POLLOUT)
    oss << "OUT ";
  if (ev & POLLHUP)
    oss << "HUP ";
  if (ev & POLLRDHUP)
    oss << "RDHUP ";
  if (ev & POLLERR)
    oss << "ERR ";
  if (ev & POLLNVAL)
    oss << "NVAL ";

  return oss.str();
}
